from flask import Blueprint, request, jsonify
from app_factory import db, bcrypt
from models import User
import logging

bp = Blueprint('auth', __name__, url_prefix='/api')
logger = logging.getLogger(__name__)

# 用户注册
@bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()

    # 验证输入
    if not data or 'email' not in data or 'password' not in data or 'name' not in data:
        return jsonify({"error": "缺少必要的字段"}), 400

    email = data['email'].strip()
    name = data['name'].strip()
    password = data['password']

    # 检查邮箱是否已存在
    if User.query.filter_by(email=email).first():
        return jsonify({"error": "该邮箱已被注册"}), 400

    # 创建新用户
    password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
    new_user = User(name=name, email=email, password_hash=password_hash)

    try:
        db.session.add(new_user)
        db.session.commit()
        return jsonify({"message": "注册成功"}), 201
    except Exception as e:
        db.session.rollback()
        logger.error(f"注册失败: {e}")
        return jsonify({"error": "注册失败，请重试"}), 500


# 用户登录
@bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()

    # 验证输入
    if not data or 'email' not in data or 'password' not in data:
        return jsonify({"error": "缺少必要的字段"}), 400

    email = data['email'].strip()
    password = data['password']

    # 查找用户
    user = User.query.filter_by(email=email).first()

    if not user or not bcrypt.check_password_hash(user.password_hash, password):
        return jsonify({"error": "邮箱或密码不正确"}), 401

    # 登录成功，生成并返回 token（这里简化为返回用户信息）
    return jsonify({
        "message": "登录成功",
        "user": {
            "id": user.id,
            "name": user.name,
            "email": user.email
        }
    }), 200